package com.trip.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.trip.config.AppUser;
import com.trip.util.AuthUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 *
 * Created by hc24 on 2017/10/3.
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){

            HandlerMethod hm= (HandlerMethod) handler;
            AppUser appUser = hm.getMethodAnnotation(AppUser.class);//from method
            if(appUser==null) {
                appUser= hm.getBeanType().getAnnotation(AppUser.class);//from controller
                if(appUser==null)
                    return true;
            }

            String authToken=request.getHeader("authToken");

            boolean authResult= AuthUtil.validAuth(authToken);
            if(!authResult){
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(401);
                PrintWriter out=response.getWriter();
                ObjectMapper om=new ObjectMapper();
                String json=om.writeValueAsString(ControllerResult.failed("Auth failed"));
                out.println(json);
                out.flush();
                out.close();

            }
            return authResult;
        }
        return true;
    }
}
